import { ref } from 'vue'
import { useIntersectionObserver, useIntervalFn } from '@vueuse/core'
const useLazyData = fn => {
  const target = ref(null)
  const { stop } = useIntersectionObserver(
    target,
    ([{ isIntersecting }]) => {
      console.log(isIntersecting, stop)
      if (isIntersecting) {
        stop()
        fn()
      }
    },
    { threshold: 0 }
  )
  return target
}
const useCountDown = () => {
  //   time : 是一个响应式数据。每隔1秒，值减一(5->4->3...)。如果在视图上使它，视图会自动更新。
  //   start: 用来启动倒计时,传入初始值。如：start(20)， time的值从20 -> 19 -> 18 ....
  //   stop: 停止倒计时
  const time = ref(0)
  // pause: 停止
  // resume: 开始
  const { pause, resume } = useIntervalFn(() => {
    time.value--
    if (time.value <= 0) {
      pause()
    }
  }, 1000, { immediate: true })
  const start = (num) => {
    time.value = num
    resume()
  }
  const stop = () => {
    pause()
  }
  return {
    time,
    start,
    stop
  }
}
export {
  useLazyData, useCountDown
}
